var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var wxAuthFail = true;

var screen_w = 320;
var inviteuid = '';
var startX = 0;
Page({
  data: {
    util: util,
    host: util.api_host,
    tc: 0,
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    version: util.version,
    token: '',
    uid: 0,
    coin: 0.00,
    userinfo: {},


    isShow: false,

    user_jifen: 0,

    has_cdb: false,


    waithao: false,
    ghsData: [],

    contact_phone: '',

    tuiwen1: '',
    tuiwen2: '',

    hiddenWidth: 59,
    btnList: [{
        right: -59
      },
      {
        right: -59
      },
      {
        right: -59
      }
    ],

    oldView: false,

    mendianId: '',
    tabcurrcata: 0,

    orgInfo: '',
  },

  onLoad: function(data) {

    var that = this;
    inviteuid = data.inviteuid ? data.inviteuid : '';

    //获取绑定小程序信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定小程序信息：", res);
      that.setData({
        orgInfo: res
      });
    });

    this.getLoginInfo(inviteuid);
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('talent-mycard/talent-mycard', function (data) {
      that.setData({
        inviteuid: inviteuid,
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        showNav: (data.shownav == 'false' ? false : true)
      });
    });
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });


    wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          windowWidth: wx.getSystemInfoSync().windowWidth,
          windowHeight: wx.getSystemInfoSync().windowHeight
        })
      }
    });

    //联系信息
    app.getAllAbout('contact', function(res) {
      that.setData({
        contact_phone: res
      })
    });

    if (data.uidfromcircle) {
      that.setData({
        navFromCircle: true,
        uidFromCircle: data.uidfromcircle
      })
      console.log('that.data.navFromCircle', that.data.uidFromCircle)
      that.getCircleUserinfo(data.uidfromcircle)
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function(responseData) {
        that.setData({
          isShow: !responseData.data.isShow
        });
      }
    });
  },

  gettuiwen: function(topicid, key) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid,
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
      data: params,
      success: function(responseData) {
        var data = responseData.data;
        console.log("啊啊啊啊啊详情：", data);
        if (key == 2) {
          that.setData({
            tuiwen2: data
          })
        } else {
          that.setData({
            tuiwen1: data
          })
        }

      }
    });
  },


  getLoginInfo: function(inviteuid) {
    var that = this;
    app.LoginUserInfo(function(res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1; //用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        token: res.token
      });

      var id = inviteuid ? inviteuid : res.uid;
      util.api({
        data: {
          "uid": id,
          "publickey": util.publiccode,
          "ac": "userinfo"
        },
        success: function(responseData) {
          console.log("用户信息", responseData.data);

          var graphic1 = responseData.data.graphic1;
          var graphic2 = responseData.data.graphic2;
          console.log("graphic1", graphic1);
          console.log("graphic2", graphic2);
          if (graphic1 != '' && graphic1 != undefined) {
            that.gettuiwen(graphic1, 1);
          }

          if (graphic2 != '' && graphic2 != undefined) {
            that.gettuiwen(graphic2, 2);
          }

          that.setData({
            userinfo: responseData.data,
            mendianId: responseData.data.mendianid,
            markers: [{
              id: 1,
              latitude: responseData.data.lat,
              longitude: responseData.data.lon,
              name: responseData.data.address
            }],
          });

          //读取供货商信息
          that.loadGHS(1);

          var tc = app.get_tc(); //简体繁体转换
          var titlename = that.data.userinfo.uname + '的' + that.data.orgInfo.uname + '名片';
          
          wx.setNavigationBarTitle({
            title: titlename,
          });
        }
      });

    });

    that.setData({
      timeStamp: new Date().getTime()
    })
  },



  //重新读取 登录用户信息
  reGetUserInfo: function(e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  goAtherPage: function(e) {
    app.saveFormId(e.detail.formId);
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },
  goAtherPageRedirect: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({
      url: url
    })
  },


  //保存formId
  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({
        url: path
      })
    }
  },
  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
  makeCallPhone: function(e) {
    app.saveFormId(e.detail.formId);
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function(e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function(e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },
  //点击图片放大
  showEWM: function(e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("showEWM", shareImgUrl)
    if (!shareImgUrl) {
      return
    }
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  //页面分享
  onShareAppMessage: function() {
    var that = this;

    var inviteuid = that.data.inviteuid ? that.data.inviteuid : that.data.uid;
    console.log("分享id2" + inviteuid);
    var textcontent = that.data.tc == 1 ? '，這是我的新名片，敬請惠存' : '，这是我的新名片，敬请惠存';

    var titleText = '我是' + that.data.userinfo.uname + textcontent;
    var option = ''
    if (that.data.room) {
      var room = that.data.room;
      textcontent = that.data.tc == 1 ? '我是' + room.building + room.number + '，歡迎入住' : '我是' + room.building + room.number + '，欢迎入住';
      titleText = textcontent;
      console.log("option", that.data.option)
      var roomstr = JSON.stringify(that.data.room)
      option = "&roomstr=" + roomstr;

    }
    return {
      title: titleText,
      path: '/pages/talent-mycard/talent-mycard?&inviteuid=' + inviteuid + option
    };
  },


  // 读取供货商信息
  loadGHS: function(cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 100
    }
    util.api({
      data: params,
      success: function(responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          console.log("that.data.mendianId = " + that.data.mendianId);
          if (that.data.mendianId) {
            var ghs_data = [];
            for (var i = 0; i < result.length; i++) {
              if (result[i].uid == that.data.mendianId) {
                ghs_data.push(result[i]);
                var videoUrl = result[i].businessVideo;
                if (videoUrl.indexOf('v.qq.com') > 0) {
                  console.log("videoUrl = " + videoUrl);
                  app.getVideoSrcLink(0, videoUrl, function(url, index) {
                    if (url != -1) {
                      var index = ghs_data.length - 1;
                      ghs_data[index].businessVideo = url;
                    }
                    that.setData({
                      ghsData: ghs_data
                    });
                    console.log("加盟的供货商数据：", ghs_data);
                  });
                } else {
                  that.setData({
                    ghsData: ghs_data
                  });
                }
                break;
              }
            }
          }
        } else {
        }
        wx.hideLoading();
      }
    });
  },

  goMapView: function(e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

  touchStart: function(e) {
    console.log("touchS" + e);
    //判断是否只有一个触摸点
    if (e.touches.length == 1) {
      //记录触摸起始位置的X坐标
      startX = e.touches[0].clientX
    }
  },

  touchMove: function(e) {
    console.log("touchM:" + e);
    var that = this
    //获取手指触摸的是哪一个item
    var index = e.currentTarget.dataset.idx;

    var list = that.data.btnList;
    if (e.touches.length == 1) {
      //记录触摸点位置的X坐标
      var moveX = e.touches[0].clientX;
      //计算手指起始点的X坐标与当前触摸点的X坐标的差值
      var disX = moveX - startX;
      //hiddenWidth 为右侧按钮区域的宽度
      var hiddenWidth = that.data.hiddenWidth;
      var txtStyle = 0;
      if (disX == 0 || disX > 0) {

        txtStyle = list[index].right > -hiddenWidth && list[index].right - disX > -hiddenWidth ? list[index].right - disX : -hiddenWidth;

      } else if (disX < 0) {
        txtStyle = -hiddenWidth - disX;
        if (-disX >= hiddenWidth) {

          txtStyle = 0;
        }
      }

      //将拼接好的样式设置到当前item中
      list[index].right = txtStyle;
      //更新列表的状态
      this.setData({
        btnList: list
      });
    }
  },

  touchEnd: function(e) {
    console.log("touchEnd:" + e);
  },

  getCircleUserinfo: function(uid) {
    var that = this;
    app.GetUserInfo(uid, function(res) {
      console.log("getCircleUserinfo:", res);
      that.setData({
        userinfo: res,
      })
      var tc = app.get_tc(); //简体繁体转换
      var titlename = tc == 1 ? '個人名片' : '个人名片';
      if (util.orgid == 15671) {
        titlename = tc == 1 ? '個人簡歷' : '个人简历';
      }
      wx.setNavigationBarTitle({
        title: that.data.userinfo.uname + titlename,
      });
    });
  },

  videoErrorCallback: function(e) {
    console.log('视频错误信息:' + e.detail.errMsg);
  },

  changeTabCata: function(e) {
    console.log("Tabcurrcata", e.currentTarget.dataset.current)
    var cur = e.currentTarget.dataset.current;
    if (this.data.tabcurrcata == cur) {
      return false;
    } else {
      this.setData({
        tabcurrcata: cur
      })
    }
  },

})